library(survey)
library(dplyr)

# Code variables of interest as binaries
summary(factor(df$Q8A))
summary(factor(df$Q8A2))

df$Q8A2[df$Q8A < 77] <- 1
df$Q8A2[df$Q8A < 3] <- 0
df$Q8B2[df$Q8B < 77] <- 0
df$Q8B2[df$Q8B < 3] <- 1
df$Q8C2[df$Q8C < 77] <- 0
df$Q8C2[df$Q8C < 3] <- 1
df$Q8D2[df$Q8D < 77] <- 0
df$Q8D2[df$Q8D < 3] <- 1
df$Q8E2[df$Q8E < 77] <- 0
df$Q8E2[df$Q8E < 3] <- 1
df$Q8F2[df$Q8F < 77] <- 0
df$Q8F2[df$Q8F < 3] <- 1
df$Q8G2[df$Q8G < 77] <- 0
df$Q8G2[df$Q8G < 3] <- 1
df$Q8H2[df$Q8H < 77] <- 0
df$Q8H2[df$Q8H < 3] <- 1


## Create weighted survey design object
w2_design <-
  svydesign(
    id = ~ 1,
    weights = ~ weight2,
    data = df
  )

# Creating Figure 4.8
x <- svyprcomp(~Q8A2 + Q8B2 + Q8C2 + Q8D2 + Q8E2 + Q8F2 + Q8H2, 
          design = w2_design, na.action = "na.omit",
          center = TRUE, scale. = TRUE, scores = TRUE)
x
summary(x)
plot.x <- biplot(x, max.alpha = 0, weight = "transparent",
                 xlim = c(-0.015,.040),
                 ylim = c(-0.015,0.03))


